package com.zhq.apputil.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;

import com.zhq.apputil.R;
import com.zhq.apputil.utils.LogUtil;
import com.zhq.apputil.utils.ScreenUtils;
import com.zhq.apputil.widget.auxlayout.RedPointDrawable;
import com.zhq.apputil.widget.bean.BadgeBean;
import com.zhq.apputil.widget.bean.IConRedDotBean;

import androidx.appcompat.widget.AppCompatTextView;


/**
 * Created by Administrator on 2017/10/26.
 */
public class IconTextView extends AppCompatTextView {
    public static final int LEFT = 0, TOP = 1, RIGHT = 2, BOTTOM = 3;
    private int mHeight, mWidth, mLocation;
    private Bitmap mImage;
    private RedPointDrawable redPointDrawable;

    public IconTextView(Context context) {
        super(context);
    }

    public IconTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public IconTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.IconTextView, defStyleAttr, 0);
        int n = a.getIndexCount();
        for (int i = 0; i < n; i++) {
            int attr = a.getIndex(i);
            if (attr == R.styleable.IconTextView_imageWidth) {
                mWidth = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_SP, 0, getResources().getDisplayMetrics()));
            } else if (attr == R.styleable.IconTextView_imageHeight) {
                mHeight = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_SP, 0, getResources().getDisplayMetrics()));
            } else if (attr == R.styleable.IconTextView_drawable_src) {
                mImage = BitmapFactory.decodeResource(getResources(), a.getResourceId(attr, 0));
            } else if (attr == R.styleable.IconTextView_imageLocation) {
                mLocation = a.getInt(attr, LEFT);
            }
        }
        a.recycle();
        drawPicture();//设置图片方法
    }


    private void drawPicture() {
        if (mImage != null) {
            Drawable mDrawable;
            if (mHeight != 0 && mWidth != 0) {
                mDrawable = new BitmapDrawable(getResources(), getRealBitmap(mImage, mWidth, mHeight));
            } else {
                mDrawable = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(mImage, mImage.getWidth(), mImage.getHeight(), true));
            }
            switch (mLocation) {
                case LEFT:
                    this.setCompoundDrawablesWithIntrinsicBounds(mDrawable, null,
                            null, null);
                    break;
                case TOP:
                    this.setCompoundDrawablesWithIntrinsicBounds(null, mDrawable,
                            null, null);
                    break;
                case RIGHT:
                    this.setCompoundDrawablesWithIntrinsicBounds(null, null,
                            mDrawable, null);
                    break;
                case BOTTOM:
                    this.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
                            mDrawable);
                    break;
            }

        }


    }

    /****
     * 是否给字体加粗
     * @param fontBold
     */
    public void setFontBold(boolean fontBold) {
        TextPaint tp = getPaint();
        tp.setFakeBoldText(fontBold);
    }

    /***
     *
     * 为iconTextView添加drawableLeft、right、bottom、right
     * @param imageResource
     * @param imageSize
     * @param mLocation
     */
    public void setIconDrawable(int imageResource, int imageSize, int mLocation) {
        Bitmap bitmap = getBitmap(imageResource);
        int size = ScreenUtils.dpToPx(getResources(), imageSize);
        Drawable mDrawable = new BitmapDrawable(getResources(), getRealBitmap(bitmap, size, size));
        switch (mLocation) {
            case LEFT:
                this.setCompoundDrawablesWithIntrinsicBounds(mDrawable, null,
                        null, null);
                break;
            case TOP:
                this.setCompoundDrawablesWithIntrinsicBounds(null, mDrawable,
                        null, null);
                break;
            case RIGHT:
                this.setCompoundDrawablesWithIntrinsicBounds(null, null,
                        mDrawable, null);
                break;
            case BOTTOM:
                this.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
                        mDrawable);
                break;
        }
    }

    /**
     * @param setRedPosition 设置红点的位置
     * @param bean           底部导航栏包装对象
     **/
    public void setIconTop(IConRedDotBean bean, int setRedPosition,int width) {
        setTextColor(bean.isSelectState() ? bean.getPressedFont() : bean.getNormalFont());
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), bean.isSelectState() ? bean.getPressedImageResources() : bean.getNormalImageResources(), options);
        Drawable mDrawable = new BitmapDrawable(getResources(), getRealBitmap(bitmap, width, width));
        this.redPointDrawable = RedPointDrawable.wrap(getContext(), mDrawable);
        BadgeBean badgeBean = bean.getBadgeBean();
        if (badgeBean.isShowRedDrawable()) {
            if (setRedPosition == badgeBean.getRedDotTotPosition()) {
                this.redPointDrawable.setColor(Color.parseColor(badgeBean.getRedDotColor()));
                this.redPointDrawable.setRadius(ScreenUtils.dpToPx(getResources(), badgeBean.getRedDotRadius()));
                this.redPointDrawable.setNumber(badgeBean.getBadgeCount());
                this.redPointDrawable.setGravity(badgeBean.getGravity());
                this.redPointDrawable.setmShowRedPoint(badgeBean.isShowRedDrawable());
            }
        }
        this.setCompoundDrawablesWithIntrinsicBounds(null, redPointDrawable,
                null, null);
        if ( !bitmap.isRecycled()) {
            bitmap.recycle();
            //LogUtil.e("释放bitmap资源....");
        }
    }


    /****
     * 已读、未读
     * @param resourceImage
     * @param iconViewSelect
     */
    public void setIconViewSelect(int resourceImage, boolean iconViewSelect, int imageSize) {
        Bitmap bitmap = getBitmap(resourceImage);
        int size = ScreenUtils.dpToPx(getResources(), imageSize);
        Drawable mDrawable = new BitmapDrawable(getResources(), getRealBitmap(bitmap, size, size));
        this.redPointDrawable = RedPointDrawable.wrap(getContext(), mDrawable);
        BadgeBean badgeBean = new BadgeBean.Builder()
                .setBadgeColor("#FF4343")
                .setBadgeRadius(3)
                .setBadgeGravity(Gravity.RIGHT)
                .setBadgeShow(iconViewSelect)
                .build();
        this.redPointDrawable.setColor(Color.parseColor(badgeBean.getRedDotColor()));
        this.redPointDrawable.setRadius(ScreenUtils.dpToPx(getResources(), badgeBean.getRedDotRadius()));
        this.redPointDrawable.setGravity(badgeBean.getGravity());
        this.redPointDrawable.setmShowRedPoint(badgeBean.isShowRedDrawable());
        this.setCompoundDrawablesWithIntrinsicBounds(redPointDrawable, null,
                null, null);
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            LogUtil.e("释放bitmap资源....");
        }
    }

    private Bitmap getBitmap(int vectorDrawableId) {
        Bitmap bitmap = null;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            Drawable vectorDrawable = getContext().getDrawable(vectorDrawableId);
            bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
                    vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            vectorDrawable.draw(canvas);
        } else {
            bitmap = BitmapFactory.decodeResource(getResources(), vectorDrawableId);
        }
        return bitmap;
    }


    public Bitmap getRealBitmap(Bitmap image, int mWidth, int mHeight) {
        //根据需要Drawable原来的大小和目标宽高进行裁剪（缩放）
        int width = image.getWidth();// 获得图片的宽高
        int height = image.getHeight();
        // 取得想要缩放的matrix参数
        float scaleWidth = (float) mWidth / width;
        float scaleHeight = (float) mHeight / height;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 返回新的Bitmap
        return Bitmap.createBitmap(image, 0, 0, width, height, matrix, true);

    }
}
